﻿using Microsoft.JSInterop;

namespace GMS.NET.Web.Components.Shared.Global.JsInterop.Cookie
{
    public class Cookie : ICookie, IAsyncDisposable
    {
        private readonly Lazy<Task<IJSObjectReference>> moduleTask;
        public Cookie(IJSRuntime jsRuntime)
        {
            moduleTask = new(() => jsRuntime.InvokeAsync<IJSObjectReference>(
                "import", "./_content/GMS.NET.Web.Components/js/GMS.NET.Cookie.js").AsTask());
        }

        public async ValueTask DisposeAsync()
        {
            if (moduleTask.IsValueCreated)
            {
                var module = await moduleTask.Value;
                await module.DisposeAsync();
            }
        }

        public async Task<string> GetCookie(string key)
        {
            var module = await moduleTask.Value;
            return await module.InvokeAsync<string>("GMSNET.GetCookie", key);
        }

        public async Task RemoveCookie(string key)
        {
            var module = await moduleTask.Value;
            await module.InvokeVoidAsync("GMSNET.RemoveCookie", key);
        }

        public async Task SetCookie(string key, string value, int s)
        {
            var module = await moduleTask.Value;
            await module.InvokeVoidAsync("GMSNET.SetCookie", key, value, s);
        }
    }
}
